//
//  UploadPhotoViewController.m
//  FaceRecognition
//
//  Created by zz on 16/12/1.
//  Copyright © 2016年 Sylar. All rights reserved.
//

#import "UploadPhotoViewController.h"
#import "RecognizeView.h"
#import "photoView.h"
#import "CustomPhotoViewController.h"

#import "PhotoResultViewController.h"
#import "UIViewController+HUD.h"
#import "WebViewController.h"
#import "FR_ManagerInfoViewController.h"

@interface UploadPhotoViewController ()<UITableViewDelegate,UITableViewDataSource,photoViewDelegate,CustomPhotoViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIAlertViewDelegate>

@property (nonatomic,strong) UITableView *tableView;

@property (nonatomic,strong) RecognizeView *tableHeaderView;

@property (nonatomic,strong) UITableViewCell *cell;

/**cell左边的属性数组*/
@property (nonatomic,strong) NSArray *leftArrs;

/**未选择photo时候的alert*/
@property (nonatomic,strong) UIAlertController *unSelectedPhotoAlert;

/**已选择photo时候的alert*/
@property (nonatomic,strong) UIAlertController *selectedPhotoAlert;

/**自定义相机*/
@property (nonatomic,strong) CustomPhotoViewController *customVc;

/**用于从相册选取照片的imagepicker*/
@property (nonatomic,strong) UIImagePickerController *imagePicker;

/**删除回调*/
@property (nonatomic,strong) photoView *selectPhotoView; //临时记录选中的selectView;
@property (nonatomic,copy) void (^delBlock)(photoView *photoView);

/**个人信息中已经存在的底片数组*/
@property (nonatomic,strong) NSMutableArray *photos;

@property (nonatomic, strong) NSMutableDictionary *infoDic; //旷视返回个人信息

/**替换后要更新的ids*/
@property (nonatomic,strong) NSMutableArray *replacePhotos;

/**传给下一个控制器的图片数量，如果点击的是没有图片的，传给下一个控制器的count需要加一，否则说明是修改的，传已有图片数量，*/
@property (nonatomic,assign) int photoCount;

@property (nonatomic,copy) NSString *scid;
@property (nonatomic,copy) NSString *scname;

@end

@implementation UploadPhotoViewController

#pragma mark -Getter
- (UITableView *)tableView{
    
    if (_tableView == nil) {
        
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, VIEW_HEIGHT - 64) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.tableFooterView = [[UIView alloc] init];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.tableHeaderView = self.tableHeaderView;
    }
    
    return _tableView;
}

- (RecognizeView *)tableHeaderView{
    
    if (_tableHeaderView == nil) {
        
        CGFloat w = (VIEW_WIDTH - 30 - 24) / 3;
        CGFloat h = 36 + w + 22;
        
        _tableHeaderView = [[RecognizeView alloc] initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, h)];
        //底片识别规范按钮点击事件
        [_tableHeaderView.specificationBtn addTarget:self action:@selector(specificationAction) forControlEvents:UIControlEventTouchUpInside];
        
        for (int i = 200; i < 203; i++) {
            
            photoView *photoV = [_tableHeaderView viewWithTag:i];
            
            photoV.delegate = self;
            
            if (_lastType == 2 ) {//家长无法管理学生底片
            
                photoV.selectBtn.hidden = YES;
                self.title = @"底片查看";
                photoV.userInteractionEnabled = false;
            }
            
            if (_lastType == 1 && _manageType == 3) {
                
                photoV.selectBtn.hidden = YES;
                self.title = @"底片查看";
                photoV.userInteractionEnabled = false;
            }
        }
    }
    
    return _tableHeaderView;
}

- (UITableViewCell *)cell{
    
    _cell = [[UITableViewCell alloc] init];
    
    UILabel *leftLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 14, 50, 16)];
    leftLabel.font = [UIFont systemFontOfSize:16];
    leftLabel.textColor = [UIColor colorWithHexString:@"#3b3b3b"];
    leftLabel.tag = 101;
    
    UILabel *rightLabel = [[UILabel alloc] initWithFrame:CGRectMake(VIEW_WIDTH - 15 - 150, 14, 150, 16)];
    rightLabel.font = [UIFont systemFontOfSize:16];
    rightLabel.textColor = [UIColor colorWithHexString:@"#979797"];
    rightLabel.textAlignment = NSTextAlignmentRight;
    rightLabel.tag = 102;
    
    //线
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(15, 43.5, VIEW_WIDTH - 15, 0.5)];
    lineView.backgroundColor = [UIColor colorWithHexString:@"#DEDEDE"];
    
    [_cell.contentView addSubview:leftLabel];
    [_cell.contentView addSubview:rightLabel];
    [_cell.contentView addSubview:lineView];
    
    return _cell;
}

- (NSArray *)leftArrs{
    
    if (_leftArrs == nil) {
        
        if (_manageType == 0) { //学生身份对应的
            
            if (_lastType == 1) {
                
                _leftArrs = @[@"姓名",@"性别",@"班级",@"师云号"];
                
            }else if(_lastType == 2){
            
                _leftArrs = @[@"姓名",@"性别",@"师云号"];
            }
            
        }else{  //管理员与员工身份下对应的
            _leftArrs = @[@"姓名",@"性别",@"学校",@"师云号"];
        }
    }
    
    return _leftArrs;
}

/**自定义相机*/
- (CustomPhotoViewController *)customVc{

    
    __weak typeof(self) weakSelf = self;
    if (_customVc == nil) {
        
        _customVc = [[CustomPhotoViewController alloc] init];
        _customVc.delegate = self;
#pragma mark -选择照片，调用编辑信息接口
        _customVc.block = ^(UIImage *image){
        
            PhotoResultViewController *resultVC = [[PhotoResultViewController alloc] init];
            resultVC.type = 1;
            resultVC.studetnId = weakSelf.model.studentid;
            resultVC.photoV = weakSelf.selectPhotoView;
            resultVC.block = ^(UIImage *image,photoView *photoV,NSNumber *photoId){
                
                if ([photoId isEqualToNumber:@-1]) { //拍照通过了手机检测,但是没有通过后台的检测
                    weakSelf.customVc = nil; //清空customVc.从新初始化
                    return;
                }
                
                if (image) {
                    
                    weakSelf.customVc = nil;
                    weakSelf.selectPhotoView.selectImage = image;
                    
                    if (photoV.photoId) { //原来有图片为替换
                        
                        [weakSelf.replacePhotos replaceObjectAtIndex:photoV.tag - 200 withObject:photoId];
                        [weakSelf editPhotos];
                    }else{
                        
                        [weakSelf.replacePhotos addObject:photoId];
                        [weakSelf editPhotos];
                    }
                    
                }else{  //没有图片时候是从新选择
                    
                    weakSelf.customVc = nil;
                    [weakSelf presentViewController:weakSelf.customVc animated:YES completion:nil];
                }
            };
            
            resultVC.oriImage = image;
            
            UIImage *image3 = [weakSelf imageWithImage:image scaledToSize:CGSizeMake(VIEW_WIDTH /2, VIEW_WIDTH /2)];
            float scale = image3.size.width/SCREENWIDTH;
            
            resultVC.selectImage = image3;
            resultVC.scale = (1 / scale);
            resultVC.faceId = weakSelf.model.faceuserid;
            
            [weakSelf presentViewController:resultVC animated:YES completion:nil];
        };
    }
    
    return _customVc;
}

- (UIAlertController *)unSelectedPhotoAlert{
    
    if (_unSelectedPhotoAlert == nil) {
        
        _unSelectedPhotoAlert = [UIAlertController alertControllerWithTitle:@"请选择获取图片的方式" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        
        UIAlertAction *openCamer = [UIAlertAction actionWithTitle:@"打开照相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            

            [self presentViewController:self.customVc animated:YES completion:nil];
            
        }];
        
        UIAlertAction *openPhotoLib = [UIAlertAction actionWithTitle:@"从手机相册获取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            _imagePicker = [[UIImagePickerController alloc] init];
            _imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            _imagePicker.delegate = self;
            _imagePicker.allowsEditing = YES;
            [self presentViewController:_imagePicker animated:YES completion:nil];
            
        }];
        
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        [_unSelectedPhotoAlert addAction:openCamer];
        [_unSelectedPhotoAlert addAction:openPhotoLib];
        [_unSelectedPhotoAlert addAction:cancel];

    }
    
    return _unSelectedPhotoAlert;
}

- (UIAlertController *)selectedPhotoAlert{
    
    if (_selectedPhotoAlert == nil) {
        
        _selectedPhotoAlert = [UIAlertController alertControllerWithTitle:@"请选择获取图片的方式" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        
        UIAlertAction *openCamera = [UIAlertAction actionWithTitle:@"打开照相机(更换)" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            [self presentViewController:self.customVc animated:YES completion:nil];
        }];
        
        UIAlertAction *openPhotoLib = [UIAlertAction actionWithTitle:@"从手机相册获取(更换)" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            _imagePicker = [[UIImagePickerController alloc] init];
            _imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            _imagePicker.delegate = self;
            _imagePicker.allowsEditing = YES;
            [self presentViewController:_imagePicker animated:YES completion:nil];
        }];
        
        UIAlertAction *delAction = [UIAlertAction actionWithTitle:@"删除照片" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            if (_delBlock) {
                
                _delBlock(_selectPhotoView);
            }
        }];
        
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        [_selectedPhotoAlert addAction:openCamera];
        [_selectedPhotoAlert addAction:openPhotoLib];
        [_selectedPhotoAlert addAction:delAction];
        [_selectedPhotoAlert addAction:cancel];
    }
    
    return _selectedPhotoAlert;
}

- (NSMutableArray *)replacePhotos{
    
    if (_replacePhotos == nil) {
        
        _replacePhotos = [NSMutableArray array];
    }
    
    return _replacePhotos;
}

#pragma mark -Setter
- (void)setPhotos:(NSMutableArray *)photos{
    
    _photos = photos;
    
    for (int i = 200; i < 200 + _photos.count; i++) {
        

        photoView *photoV = [self.tableHeaderView viewWithTag:i];
        
        photoV.delegate = self;
        
        NSDictionary *dict = _photos[i - 200];
        NSString *urlStr = [dict objectForKey:@"url"];
        photoV.photoId = [dict objectForKey:@"id"];
        [photoV.photoImageView sd_setImageWithURL:[NSURL URLWithString:urlStr] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
           
            photoV.selectImage = image;
        }];
    }
}



#pragma mark -LifeCycle

- (instancetype)init{
    
    if (self = [super init]) {
        
        self.hidesBottomBarWhenPushed = YES;
    }
    
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIBarButtonItem *left = [[UIBarButtonItem alloc] initWithImage:[UIImage imageWithOriginalName:@"back"] style:UIBarButtonItemStyleDone target:self action:@selector(back)];
    
    self.title = @"底片管理";
    self.navigationItem.leftBarButtonItem = left;
    
    
    [self.view addSubview:self.tableView];
    
    //登录旷视
    [self loginForFaceInfomation];
}

#pragma mark -UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return _lastType == 1 ? 4 : 3;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell *cell = self.cell;
    UILabel *leftLabel = (UILabel *)[cell.contentView viewWithTag:101];
    UILabel *rightLabel = (UILabel *)[cell.contentView viewWithTag:102];
    
    leftLabel.text = self.leftArrs[indexPath.row];
    
    
    
    NSString *contentStr;
    
    switch (indexPath.row) {
        case 0:
            contentStr = _model.studentname ? _model.studentname : _model.username;
            break;
        case 1:
            
            if (_manageType == 1 || _manageType == 5 || _manageType == 4 || _manageType == 3) {
                
                _model.studentsex = _model.sex;
            }
            
            if (_model.studentsex == 1) {
                contentStr = @"女";
            }else if (_model.studentsex == -1){
                contentStr = @"待完善";
            }else{
                contentStr = @"男";
            }
        
            break;
        case 2:
            contentStr = _model.classname;
            
            if (_manageType == 0) {
                
                if (_lastType == 1) {
                    
                    contentStr = _model.classname;
                }else if (_lastType == 2){
                    
                    contentStr = _model.studentid;
                }
                
            }else{

                contentStr = _scname;
            }
            break;
        case 3:
        
            contentStr = _model.studentid ?  _model.studentid : _model.userid;
            
            break;
        default:
            break;
    }
    
    rightLabel.text = contentStr;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

#pragma mark -Action

//返回上一层控制器
- (void)back{

//    for (UIViewController *vc in self.navigationController.childViewControllers) {
//        
//        if ([vc isKindOfClass:[FR_ManagerInfoViewController class]]) {
//            
//            [self.navigationController popToViewController:vc animated:YES];
//        }
//    }
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)specificationAction{
    
    WebViewController *webvc = [[WebViewController alloc] init];
    webvc.requestURL = @"http://api2.our100.net/about/sysm/rlsb.html";
    webvc.controllerTitle = @"照片识别规范";
    webvc.type = 1;
    [self presentViewController:webvc animated:YES completion:nil];
}

#pragma mark -photoViewDelegate
- (void)selectPhoto:(photoView *)photoV{
    
    if (_lastType == 2) {
        
        return;
    }
    //记录选择了哪一个photoview
    _selectPhotoView = photoV;
    
    UIImage *selectImage = photoV.selectImage;
        
    if (!selectImage) { //没有图片，时候的选择
        
        [self presentViewController:self.unSelectedPhotoAlert animated:YES completion:nil];
    }else{  //有图片时候的选择
        
        __weak typeof(self) weakSelf = self;
        _delBlock = ^(photoView *p){  //回调删除block
            
            [weakSelf.replacePhotos removeObjectAtIndex:photoV.tag - 200];
            p.photoId = nil;
            [weakSelf editPhotos];
            
            p.selectImage = nil;
        };
        
        [self presentViewController:self.selectedPhotoAlert animated:YES completion:nil];
    }
    
}

#pragma mark  -调用旷视修改个人信息接口
- (void)editPhotos{
   
  
    [self.infoDic setObject:self.replacePhotos forKey:@"photo_ids"];
   
    [Utils editInfo:@"/subject/[id]" parameters:self.infoDic success:^(NSURLSessionDataTask *task, id jsonobject) {
       
       NSLog(@"jsonobject ** = %@",jsonobject);
       
        NSDictionary *dict = [jsonobject objectForKey:@"data"];
        NSArray *photos = [dict objectForKey:@"photos"];
        
        NSInteger count = photos.count;
        
        //修改上一个界面对应的张数
        _selectedCell.countLabel.text = [NSString stringWithFormat:@"%ld张",(long)count];
        
        //调用师云服务器，通知后台底片数量
        [self Jave_callShiyunServerWithCount:count];
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        [self showHint:error.localizedDescription];
    }];

}

#pragma mark -callShiyunServer
- (void)Jave_callShiyunServerWithCount:(NSInteger)count {
    RequestParam *param = [RequestParam param];
    
    NSString *scid;
    
    if (![_model.scid isEqualToString:@"0"] && _model.scid) {
        scid = _model.scid;
    }else{
        scid = [NSString stringWithFormat:@"%@",_scid];
    }
    
    if (!_scid) {
        [self showHint:@"请传入scid"]; return;
    }
    
    param.scid = scid;
    param.studentid = _model.studentid ? _model.studentid : _model.userid;
    param.faceuserid = _model.faceuserid;
    
    
    [Utils Java_get:@"api/facePhotoAdd" parameters:param.mj_keyValues success:^(NSInteger recode, id jsonObject) {
        
    } failure:^(NSInteger recode, NSError *error) {
        [self showHint:error.localizedDescription];
    }];
    
}

#pragma mark -customPhotoViewDelegate

//取消相机拍摄
- (void)cancelCameraAction:(id)sender{
    
    [self.customVc dismissViewControllerAnimated:YES completion:nil];
    _customVc = nil;
}

#pragma mark -Private
- (void)loginForFaceInfomation{
    
    NSMutableDictionary *paramDic = [[NSMutableDictionary alloc]init];
    
    if (_model.userid) {
        [paramDic setObject:_model.userid forKey:@"userid"];
    }else if (_model.studentid) {
        [paramDic setObject:_model.studentid forKey:@"userid"];
    }
    
    NSString *scid;
    
    if (_lastType == 1) {
        
        scid = [SYAccountTool ShareAccount].account.scid;
    }else if(_lastType == 2) { //从学生模型里取
        
        scid = _model.scid;
    }
    
    if (!scid) {
        //[self showHint:@"没有scid getFaceServerInfo无法正常调用"];
        return;
    }
    
    [paramDic setObject:scid forKey:@"scid"];
    
    [Utils Java_get:@"api/getFaceServerInfo" parameters:paramDic success:^(NSInteger recode, id jsonObject) {
       
        NSDictionary *dict = [jsonObject objectForKey:@"re_data"];
        
        if ([dict isKindOfClass:[NSArray class]]) {
            
            dict = [(NSArray *)dict firstObject];
        }
        
        _scid = [dict objectForKey:@"scid"];
        if (dict.allKeys.count == 0) {
            return;
        }
        
        //得到返回的用户名的密码
        NSString *loginName = [dict objectForKey:@"loginname"];
        NSString *loginPass = [dict objectForKey:@"loginpass"];
        _scname = [dict objectForKey:@"scname"];
        
        //拼接字典,做参数传给登录旷世的接口
        NSMutableDictionary *dictM = [NSMutableDictionary dictionary];
        [dictM setObject:loginName forKey:@"username"];
        [dictM setObject:loginPass forKey:@"password"];
        
        
        NSHTTPCookie *cookie = [[[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[NSURL URLWithString:@"https://v2.koalacam.net"]] firstObject];
        [[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];
        
        if (_manageType == 1 || _manageType == 3 || _manageType == 4 || _manageType == 5) {
            
            [self.tableView reloadData];
        }
        
        //调用登录旷世接口
        [self loginForCookie:dictM];
        
    }failure:^(NSInteger recode, NSError *error) {
        
    }];
    
}

#pragma mark -登录旷视
/**登录旷世，获取到cookie*/
- (void)loginForCookie:(NSMutableDictionary *)dict{

    [Utils loginKuangshi:nil parameters:dict success:^(AFHTTPResponseSerializer *option, id responjson) {
        
//        NSArray *arr = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
        
        
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        
        [dict setObject:_model.faceuserid forKey:@"id"];
        
        //登录成功后  获取个人信息
        [Utils getInfoByid:@"/subject/[id]" parameters:dict success:^(NSURLSessionDataTask *task, id responjson) {
            
            int code = [[responjson objectForKey:@"code"] intValue];
            NSString *desc = [responjson objectForKey:@"desc"];
            if (code != 0) {
                
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:desc delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil];
                [alert show];
                return;
            }
            
            NSDictionary *dict = [responjson objectForKey:@"data"];
            self.photos = [dict objectForKey:@"photos"];
            
            self.infoDic = [dict mutableCopy];
            for (NSDictionary *dic in self.photos) {
                
                NSNumber *num = [dic objectForKey:@"id"];
                [self.replacePhotos addObject:num];
            }
            
        } failure:^(NSURLSessionDataTask *task, NSError *error) {
            
        }];
        
    } failure:^(AFHTTPResponseSerializer *option, NSError *error) {
        
        [self showHint:@"旷世接口登录失败,请从新登录"];
        
    }];
}

#pragma mark -裁剪照片
-(UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize
{
    
    int tempWidth = image.size.width;
    int tempHeight = image.size.height;
    
    UIImage *resultImg=nil;
    
    if(tempWidth <= newSize.width && tempHeight <= newSize.height)
        resultImg=image;
    else
    {
        float tempRate = (float)newSize.width/tempWidth < (float)newSize.height/tempHeight ? (float)newSize.width/tempWidth : (float)newSize.height/tempHeight;
        CGSize itemSize = CGSizeMake(tempRate*tempWidth, tempRate*tempHeight);
        UIGraphicsBeginImageContext(itemSize);
        CGRect imageRect = CGRectMake(0, 0,itemSize.width,itemSize.height);
        [image drawInRect:imageRect];
        resultImg= UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    }
    
    
    return resultImg;
}

#pragma mark -UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    [self.imagePicker dismissViewControllerAnimated:YES completion:nil];
    
    UIImage *image = info[UIImagePickerControllerEditedImage];
    
    PhotoResultViewController *resultVC = [[PhotoResultViewController alloc] init];
    resultVC.selectImage = image;
    resultVC.oriImage = image;
    resultVC.scale = 1.0f;
    resultVC.type = 2;
    resultVC.faceId = _model.faceuserid;
    resultVC.studetnId = _model.studentid ? _model.studentid : _model.userid; //学生模型没有studentid
    resultVC.photoV = _selectPhotoView;
    
    __weak typeof(self) weakSelf = self;
    
    resultVC.block = ^(UIImage *image,photoView *photoV,NSNumber *photoId){
        
        if (image) {
            
            weakSelf.customVc = nil;
            weakSelf.selectPhotoView.selectImage = image;
            if (photoV.photoId) {
                
                [weakSelf.replacePhotos replaceObjectAtIndex:photoV.tag - 200 withObject:photoId];
                //调用班级旷世的修改底片接口，修改对应位置的底片
                [weakSelf editPhotos];
            }else{
             
                [weakSelf.replacePhotos addObject:photoId];
                [weakSelf editPhotos];
            }
            
        }else{  //没有图片时候是从新选择
            
            [weakSelf presentViewController:weakSelf.imagePicker animated:YES completion:nil];
        }
    };
    
    [self presentViewController:resultVC animated:YES completion:nil];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    [self.navigationController popViewControllerAnimated:YES];
}
@end
